package cn.edu.seu.herald.informationplatform.dao.cookie;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import cn.edu.seu.herald.informationplatform.bean.auth.UserSession;
import cn.edu.seu.herald.informationplatform.bean.league.User;
import cn.edu.seu.herald.informationplatform.dao.database.UserDao;
import cn.edu.seu.herald.informationplatform.dao.database.UserSessionDao;

public class CommonUserSessionCookieAccess extends SessionCookieAccess {
	
	private UserSessionDao _userSessionDao;

	private static String SESSION_ID_COOKIE_NAME = "COMMON_USER_SESSION_ID";
	
	public CommonUserSessionCookieAccess(HttpServletRequest request)
				throws SessionIdNotFound {
		super(request);
		_userSessionDao = UserSessionDao.getDao();
	}

	@Override
	public boolean isAuthorized() throws SQLException {
		int id = Integer.valueOf(getSessionId());
		return _userSessionDao.contains(id);
	}
	
	public int getUserId() throws SQLException {
		int id = Integer.valueOf(getSessionId());
		UserSession userSession = _userSessionDao.getUserSessionById(id);
		int userId = userSession.getUserId();
		return userId;
	}

	@Override
	public String getUsername() throws SQLException {
		int userId = getUserId();
		UserDao userAccess = UserDao.getDao();
		User user = userAccess.getUserById(userId);
		return user.getTruename();
	}

	@Override
	protected String getSessionIdName() {
		return SESSION_ID_COOKIE_NAME;
	}

}
